package com.incar.chuxing.application;

import android.content.Context;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.incar.chuxing.BuildConfig;
import com.incar.chuxing.api.ApiStore;
import com.incar.chuxing.api.ConfigApiStore;
import com.incar.chuxing.api.UrlContainer;
import com.incar.chuxing.bean.AppConstants;
import com.incar.chuxing.bean.ConfigEvent;
import com.incar.chuxing.utils.Logger;
import com.incar.chuxing.utils.SPKey;
import com.incar.chuxing.utils.SPUtils;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Type;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by michaelpi on 2018/6/11.
 */

public class GetAppConfig {
    private static GetAppConfig instance;
    private Context mContext;
    public boolean isUpdate = false;//apiConfig是否加载成功

    public interface UpdateDone {
        void onUpdateDone();
    }

    public static GetAppConfig getInstance(Context context) {
        if (instance == null) {
            instance = new GetAppConfig(context);
        }
        return instance;
    }

    private GetAppConfig(Context context) {
        mContext = context;
    }

    public void getConfig(UpdateDone updateDone) {
        if (BuildConfig.DEBUG) {
            switch (SPUtils.getInstance(mContext).getIntValue("$s_urlMode")) {
                case 0://默认
                case 2://test
                case 3://pro
                case 6:
                    //0 2 3 6需要调用apiConfig
                    break;
                default://无需调用apiConfig，如果调用了直接回调告知成功
                    if (updateDone != null) {
                        updateDone.onUpdateDone();
                    }
                    return;
            }
        }

        ConfigApiStore.getInstance().getApiService(UrlContainer.Request.BASE_CONFIG_URL).appConfig(MyApplication.getInstance().getAppVersion(), "android").enqueue(new Callback<JsonObject>() {
            @Override
            public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                if (response.isSuccessful() && response.body() != null) {
                    Logger.i("apiConfig", "get config ok");
                    setUrl(response.body());
                } else {
                    Logger.i("apiConfig", "get config err");
                }
                if (updateDone != null) {
                    updateDone.onUpdateDone();
                }
            }

            @Override
            public void onFailure(Call<JsonObject> call, Throwable t) {
                //ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                isUpdate = true;//apiConfig已加载过
                if (updateDone != null) {
                    updateDone.onUpdateDone();
                }
                Logger.i("apiConfig", "get config failure" + t.getMessage());
            }
        });
    }

    private void setUrl(JsonObject jsonObject) {
        try {
            JsonObject jsonApi = jsonObject.getAsJsonObject("data").getAsJsonObject("common");
            Map<String, String> apiMap = UrlContainer.Request.h5UrlMap;

            Type typeApi = new TypeToken<Map<String, String>>() {
            }.getType();

            apiMap.putAll(new Gson().fromJson(jsonApi.getAsJsonObject("server_url").toString(), typeApi));
            apiMap.putAll(new Gson().fromJson(jsonApi.getAsJsonObject("h5_url").toString(), typeApi));
            apiMap.put("imgPrefixUrl", jsonApi.get("imgPrefixUrl").getAsString());
            apiMap.put("shotACarUrl", jsonApi.get("shotACarUrl").getAsString());
            int parkFeeEntry = jsonObject.getAsJsonObject("data").getAsJsonObject("android").getAsJsonObject("feature_on_off").get("allowparkingFeeEntry").getAsInt();
            int webOrderHistory = jsonObject.getAsJsonObject("data").getAsJsonObject("android").getAsJsonObject("feature_on_off").get("allowWebOrderHistory").getAsInt();
            int parkTypeSelect = jsonObject.getAsJsonObject("data").getAsJsonObject("android").getAsJsonObject("feature_on_off").get("free_parking_select_show").getAsInt();
            int changXingCard = jsonObject.getAsJsonObject("data").getAsJsonObject("android").getAsJsonObject("feature_on_off").get("changXingCard").getAsInt();
            int myOilTank = jsonObject.getAsJsonObject("data").getAsJsonObject("android").getAsJsonObject("feature_on_off").get("myOilTank").getAsInt();
            int shareCar = jsonObject.getAsJsonObject("data").getAsJsonObject("android").getAsJsonObject("feature_on_off").get("shareCar").getAsInt();
            int exclusiveCar = jsonObject.getAsJsonObject("data").getAsJsonObject("android").getAsJsonObject("feature_on_off").get("exclusiveCar").getAsInt();
            int shotACar = jsonObject.getAsJsonObject("data").getAsJsonObject("android").getAsJsonObject("feature_on_off").get("shotACar").getAsInt();
            SPUtils.getInstance(mContext).putIntValue(SPKey.PARK_FEE_ENTRY, webOrderHistory);
            SPUtils.getInstance(mContext).putIntValue(SPKey.WEB_ORDER_HISTORY, parkFeeEntry);
            SPUtils.getInstance(mContext).putIntValue(SPKey.PARK_TYPE_SELECT, parkTypeSelect);
            SPUtils.getInstance(mContext).putIntValue(SPKey.CHANG_XING_CARD, changXingCard);
            SPUtils.getInstance(mContext).putIntValue(SPKey.MY_OIL_TANK, myOilTank);
            SPUtils.getInstance(mContext).putIntValue(SPKey.SHARE_CAR, shareCar);
            SPUtils.getInstance(mContext).putIntValue(SPKey.EXCLUSIVE_CAR, exclusiveCar);
            SPUtils.getInstance(mContext).putIntValue(SPKey.SHOT_CAR, shotACar);
            UrlContainer.Request.BASE_GATE_URL = apiMap.get(UrlContainer.Request.apiServerNewV2);
            //图片地址
            ((MyApplication) mContext.getApplicationContext()).setImageUrl(apiMap.get("imgPrefixUrl"));
            Logger.d("apiConfig", "net load url set");
        } catch (Exception e) {
            e.printStackTrace();
        }
        isUpdate = true;//apiConfig已加载成功
    }


    public void getAppConstants() {
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_CONFIG_URL).getAppConstants(MyApplication.getInstance().getAppVersion(), "android").enqueue(new Callback<AppConstants>() {
            @Override
            public void onResponse(Call<AppConstants> call, final Response<AppConstants> response) {
                if (response.isSuccessful() && response.body() != null && response.body().getMsg_code() == 200 && response.body().getData() != null) {
                    SPUtils.getInstance(mContext).putStringValue(SPKey.HOT_LINE, response.body().getData().getServiceTel());
                    SPUtils.getInstance(mContext).putIntValue(SPKey.MAX_OCR_COUNT, response.body().getData().getMaxOCRcount());
                    SPUtils.getInstance(mContext).putStringValue(SPKey.RETURN_CAR_MESSAGE, response.body().getData().getReturnCarMessage());
                    if (response.body().getData().getReturnCarPositionOptions() != null) {
                        SPUtils.getInstance(mContext).putStringValue(SPKey.RETURN_CAR_OPTIONS, new Gson().toJson(response.body().getData().getReturnCarPositionOptions()));
                    }

                    if (response.body().getData().getRentalDaysOptions() != null) {
                        SPUtils.getInstance(mContext).putStringValue(SPKey.DAY_RENT_OPTIONS, new Gson().toJson(response.body().getData().getRentalDaysOptions()));
                    }
                    if (response.body().getData().getRentalLittleDaysOptions() != null) {
                        SPUtils.getInstance(mContext).putStringValue(SPKey.LITTLE_DAY_RENT_OPTIONS_DURATION, new Gson().toJson(response.body().getData().getRentalLittleDaysOptions()));
                    }

                    SPUtils.getInstance(mContext).putIntValue(SPKey.DAY_RENT_DURATION, response.body().getData().getMaxRentalDayTime());


                    if (response.body().getData().getText() != null) {
                        try {
                            SPUtils.getInstance(mContext).putStringValue(SPKey.DAY_RENT_TIP_TOP, response.body().getData().getText().getPreOrderDailyRentailFeeTopDes());
                            SPUtils.getInstance(mContext).putStringValue(SPKey.DAY_RENT_TIP_BOTTOM, response.body().getData().getText().getPreOrderDailyRentailFeeBottomDes());
                            SPUtils.getInstance(mContext).putStringValue(SPKey.ABATEMENT_TIP, response.body().getData().getText().getPreOrderInsuranceExplain());
                            SPUtils.getInstance(mContext).putStringValue(SPKey.PARK_TYPE_TIP, response.body().getData().getText().getFree_parkingAlertText());
                            SPUtils.getInstance(mContext).putStringValue(SPKey.DAY_RENT_TIP_TOP2, response.body().getData().getText().getScpreOrderDailyRentailFeeTopDes());
                            SPUtils.getInstance(mContext).putStringValue(SPKey.TOP_BANNER_TEXT0, response.body().getData().getTopBannerArr().get(0));
                            SPUtils.getInstance(mContext).putStringValue(SPKey.TOP_BANNER_TEXT1, response.body().getData().getTopBannerArr().get(1));
                            SPUtils.getInstance(mContext).putStringValue(SPKey.TOP_BANNER_TEXT2, response.body().getData().getTopBannerArr().get(2));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    Logger.i("apiConfig", "invoke getAppConstants ok");
                } else {
                    Logger.i("apiConfig", "invoke getAooConstants server Error");
                    SPUtils.getInstance(mContext).putIntValue(SPKey.MAX_OCR_COUNT, 20);
                }
                EventBus.getDefault().post(new ConfigEvent(true));
            }

            @Override
            public void onFailure(Call<AppConstants> call, Throwable t) {
                //ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                Logger.i("apiConfig", "invoke getAooConstants failure" + t.getMessage());
                SPUtils.getInstance(mContext).putIntValue(SPKey.MAX_OCR_COUNT, 20);
                EventBus.getDefault().post(new ConfigEvent(true));
            }
        });
    }

}
